<?php defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

/* JoomLeague League Management and Prediction Game for Joomla!
 * @version $Id: joomleague.php 1235 2008-07-18 13:04:34Z julienv $
 * @package Joomleague
 * @copyright Copyright (C) 2007  JoomLeague
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see _joomleague_license.txt
 *    
 * Homepage: http://www.joomleague.de
 * Support: htt://www.joomleague.de/forum/
 * 
 * This file is part of JoomLeague.
 *  
 * JoomLeague is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * Please note that the GPL states that any headers in files and
 * Copyright notices as well as credits in headers, source files
 * and output (screens, prints, etc.) can not be removed.
 * You can extend them with your own credits, though...
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * The "GNU General Public License" (GPL) is available at
 * http://www.gnu.org/copyleft/gpl.html.
*/ 

//##########################################################################################################################
// PHP error reporting, comment out if needed

//error_reporting(E_ERROR | E_PARSE);

// PHP error reporting END
//##########################################################################################################################

// defines for global vars
global $database, $mainframe;

global $joomleague, $joomleague_tabs;

require_once $mainframe->getPath( 'class' );

// Language selection - START
if (file_exists(JL_FRONTEND_PATH.'/language/'._JL_LANG.'.php')) {
  include(JL_FRONTEND_PATH.'/language/'._JL_LANG.'.php');
}
else {
  include(JL_FRONTEND_PATH.'/language/english.php');
}
// Language Selection - END

// loading all required classes
require_once( $mainframe->getPath( 'front_html', 'com_joomleague' ) );
require_once JL_FRONTEND_PATH.'/images/joomleague/Thumb.class.php';
// loading all required classes ends

// load general configuration file
global $jlgConfig;
if ( file_exists( JL_ADMIN_PATH."/jlgconfig.php" ) ) {
  include_once(JL_ADMIN_PATH."/jlgconfig.php" );
} 

/**
 * Instantiate the default html helper.
 */
global $htmlHelper;
$htmlHelper = new HTML_joomleague();

// Predictions functions have moved
//search for:
// Prediction game starts
// in this file to get there

// Permissions: Check for administrators and moderators
if ($my->id != 0) {
    $aro_group = $acl->getAroGroup($my->id);
    if (strtolower($aro_group->name) == 'super administrator' || strtolower($aro_group->name) == 'administrator') {
      define('JL_USER_IS_BIG_BOSS', TRUE);
    }
}

// we now load joomleague.js (fka joomleague.js.php) right here to header
// template calls are removed (conflict with mootools in stupid ie)
$mainframe->addCustomHeadTag( '<script src="'.JL_URL_FOLDER.'/js/joomleague.js" type="text/javascript"></script>' ); 
//##########################################################################################################################
$option       = mosGetParam( $_REQUEST , 'option' , 'com_joomleague' );
$jl_func      = strtolower( mosGetParam( $_REQUEST , 'func' , 'frontpage' ) );
$p            = intval( mosGetParam( $_REQUEST, 'p', 0 ) );     // project_id

//##########################################################################################################################
//##########################################################################################################################
//##########################################################################################################################
// Start der verschiedenen Funktionen

// first handle the function that are independant of projects
if ( !switchGeneralFunc( $jl_func ) )
{
  // general function didn't trigger on specified $jl_func
	// call project specific functions handler if a project was specified
	$joomleague = new JoomLeague( $database);
	if ( $p && $joomleague->load($p) ) {
    switchProjectFunc( $jl_func );
	}
	else {
		switchGeneralFunc( 'frontpage' );
	}
}

function switchProjectFunc( $jl_func )
{
	global $my, $mainframe, $database;
  global $joomleague, $joomleague_tabs, $jlgConfig, $htmlHelper, $overall_config;
  
  $pid          = intval(mosGetParam($_REQUEST, 'pid', 0));   // playertoolid
	$tid          = intval(mosGetParam($_REQUEST, 'tid', 0));   // teamid
	$teamtoolid   = intval(mosGetParam($_REQUEST, 'ttid', 0));  // teamid
	$cid          = intval(mosGetParam($_REQUEST, 'cid', 0));   // clubid
	$mid          = intval(mosGetParam($_REQUEST, 'mid', 0));   // match_id
	$cids         = mosGetParam($_POST, 'cids', array(0));      // array
	$pgid         = intval(mosGetParam($_REQUEST, 'pgid', 0));  //playgroundid
	$uid          = intval(mosGetParam($_REQUEST, 'uid', 0));   // user_id
	$r            = intval(mosGetParam($_REQUEST, 'r', 0));     // round param
	$p            = $joomleague->id;                            // shortcut for project id
	
  $regular_output = (intval(mosGetParam($_REQUEST, 'no_html', 0)) == 1) ? false : true;

	  
  // template used
  $folder = $joomleague->template;
  
  // tell program path to templates for this project
  define('JL_TEMPLATE_PATH', JL_FRONTEND_PATH.'/frontend/'.$folder);  
  // tell program where to find images / css 
  define('JL_TEMPLATE_FOLDERS_URL', _JOOMLA_JL_LIVE_SITE.'/components/com_joomleague/frontend/'.$folder);
  
	// user permissions
  if ( $my->id > 0 && $my->id == $joomleague->joomleague_admin ) {
    define('JL_USER_IS_PROJECT_ADMIN', TRUE);
  }
  if ( $my->id > 0 && $my->id == $joomleague->joomleague_editor ) {
    define('JL_USER_IS_PROJECT_EDITOR', TRUE);
  }
    
  // check whether a prediction game is enabled for this project
  if ( $joomleague->usePrediction() ) {
    define('JL_PREDICTION', TRUE);
  }
  
  // moved function to increase round to Joomleague.Class Gucky 2007/05/15 
  if ($joomleague->current_round_auto > 0) {
    $joomleague->increaseRound();
  }
  if($teamtoolid > 0) {
    $teamtool = new TeamTool($database);
    $teamtool->load($teamtoolid);
  }
  
  // load overall config by default
  $overall_config = $joomleague->getTemplateConfig( "overall.tpl" );
  if ( ! isset( $overall_config['project_heading_type'] ) ) {
    $overall_config['project_heading_type'] = 0;
  }
  $overall_config = array_merge($overall_config, $jlgConfig);
  
	// if we are using a custom template, include its controller.php file first if it exists
	if ( $folder != 'default' && file_exists(JL_TEMPLATE_PATH.'/'.'controller.php') ) {
	  include (JL_TEMPLATE_PATH.'/'.'controller.php');
	}

  // start switching
	switch( $jl_func )
	{
		case "upload_form":
	  	if ($my->id>0) {
	    	$showUser_config=$joomleague->getTemplateConfig("show_user.tpl");
	    	$filesize=(isset($showUser_config['filesize'])) ? $showUser_config['filesize']*1024 : intval(51200/1024);
	    	$filetypes=(isset($showUser_config['filetype'])) ? $showUser_config['filetype'] : '.jpeg, .jpg, .png, .gif';
	    	$regular_output = false;
	  		require(getTemplateFile(JL_TEMPLATE_PATH, 'upload.tpl.php'));
	  	}
	  	break;
		case "del_userpic":
			$uid=$my->id;
			$picture=mosGetParam($_REQUEST, "picture", '');
		  $showUser_config=$joomleague->getTemplateConfig("show_user.tpl");
		  $regular_output = false;
		  $filedir = 'images/joomleague/users';
		  if ($picture!=''&&$uid>0) {
		  	unlink (_JOOMLA_JL_PATH.'/'.$filedir.'/'.$picture);
		  	unlink (_JOOMLA_JL_PATH.'/'.$filedir.'/tn_'.$picture);
		  	$query="UPDATE #__joomleague_tip_members SET picture = NULL WHERE user_id = $uid";
		  	$database->setQuery($query);
		  	$database->query();
		  	echo '<div style="font-family:Verdana;font-size:11px;">Picture <b>'._JOOMLA_JL_LIVE_SITE.'/'.$filedir.'/'.$picture.'</b> has been deleted!'.
		  	     ' <a href="'._JOOMLA_JL_LIVE_SITE.'/'.JL_COMPONENT_LINK_NOHTML.'&amp;func=upload_form&amp;p='.$joomleague->id.'">Back</a></div>';
		  	?>
				<script type="text/javascript">
				// <![CDATA[
				<!--
				window.parent.document.getElementById('delPicture').style.display = 'none';
				//-->
				// ]]>
				</script>
				<?php
		  }
		  else echo '<div style="font-family:Verdana;font-size:11px;">no picture sent</div>';
			break;
			
		case "upload_userpic":
			if ($my->id>0) {
				$regular_output = false;
				$showUser_config=$joomleague->getTemplateConfig("show_user.tpl");
				$filedir = '/images/joomleague/users/';
				$dirstringstart = ($filedir{0}=='/') ? 1 : 0;
				$dirstringend = ($filedir{strlen($filedir)-1}=='/') ? strlen($filedir)-2 : strlen($filedir)-1;
				$filedir = substr($filedir, $dirstringstart, $dirstringend);
				if (!is_dir(_JOOMLA_JL_PATH.'/'.$filedir.'/upload_logs')) {
					$createdirs=explode("/", $filedir);
					$thisdir='';
					foreach ($createdirs AS $dir) {
						$thisdir.='/'.$dir;
						if (!is_dir(_JOOMLA_JL_PATH.'/'.$thisdir)) {
							mkdir(_JOOMLA_JL_PATH.'/'.$thisdir);
							copy(_JOOMLA_JL_PATH.'/images/index.html', _JOOMLA_JL_PATH.'/'.$thisdir.'/index.html');
						}
					}
					if (!is_dir(_JOOMLA_JL_PATH.'/'.$thisdir.'/upload_logs')) {
						mkdir(_JOOMLA_JL_PATH.'/'.$thisdir.'/upload_logs');
						copy(_JOOMLA_JL_PATH.'/images/index.html', _JOOMLA_JL_PATH.'/'.$thisdir.'/upload_logs/index.html');
					}
				}
				$pictype='';
				if  (preg_match("/^image\/(pjpeg|jpeg)$/", $_FILES['userfile']['type'])) $pictype =".jpg";
				elseif (preg_match("/^image\/gif$/", $_FILES['userfile']['type'])) $pictype =".gif";
				elseif  (preg_match("/^image\/png$/", $_FILES['userfile']['type'])) $pictype =".png";
				//$myfilename=trim(strtolower(str_replace(" ", "", $_FILES['userfile']['name'])));
		
				$upload_class  = new Upload_Files;
				$upload_class -> temp_file_name    = trim($_FILES['userfile']['tmp_name']);
				$upload_class -> file_name         = $my->id.$pictype;
				$filename=$my->id.$pictype;
				$upload_class -> upload_dir        = _JOOMLA_JL_PATH.'/'.$filedir.'/';
				$upload_class -> upload_log_dir    = _JOOMLA_JL_PATH.'/'.$filedir.'/upload_logs/';
				$upload_class -> max_file_size     = (isset($showUser_config['filesize'])) ? $showUser_config['filesize'] * 1024 : 51200;
				// banned user array
				$upload_class -> banned_array      = array("");
				// permitted file extension array
				$upload_class -> ext_array         = (isset($showUser_config['filetype'])) ? explode (",", $showUser_config['filetype']) : array(".jpeg",".jpg",".png",".gif");
				// validate extension
				$valid_ext     = $upload_class->validate_extension();
				 
				$is_image     = $upload_class->is_image();
				// validate size
				$valid_size    = $upload_class->validate_size();
				// validate user
				$valid_user    = $upload_class->validate_user();
				// get maximum file size
				$max_size      = $upload_class->get_max_size();
				// get file size
				$file_size     = $upload_class->get_file_size();
				// check if the file already exists
				$file_exists   = $upload_class->existing_file();
		
				// return path
				$extra = "<a href='JavaScript:history.go(-1);'>Back</a>";
		
				// start checking
				if ($valid_ext&&!$is_image)
				{
					$result = "STUPID OR SOMETHING! TRIED TO FOOL ME WITH A NON IMAGE FILE!!! ".$extra;
				}
				elseif (!$valid_ext)
				{
					$result = "The file extension is invalid, please try again! ".$extra;
				}
				elseif (!$valid_size)
				{
					$result = "The file size is invalid, please try again! The maximum file size is: $max_size and your file was: $file_size ".$extra;
				}
				elseif (!$valid_user)
				{
					$result = "You have been banned from uploading to this server. ".$extra;
				}
				elseif ($file_exists)
				{
					$result = "This file already exists on the server, please try again. ".$extra;
				}
				else {
					$upload_file = $upload_class->upload_file_with_validation();
					if (!$upload_file) {
						$result = "Your file could not be uploaded! ".$extra;
					}
					else {
						$result = "Your file has been successfully uploaded to the server.";
						$picturesrc=$filedir.'/'.$my->id.$pictype;
						// name you want to give to the thumbnail (again - don't forget the path)
						$new_name=$filedir.'/tn_'.$my->id.$pictype;
						$wanted_size=20;
						$report=0;
						$resizer=new thumbnailit;
						$thumbnail=$resizer->ResizeImg($picturesrc,$new_name,$wanted_size,$report);
						$picture = sprintf('<img src="%s/%s" style="max-width:150px;max-height:150px;" />', _JOOMLA_JL_LIVE_SITE, $picturesrc);
						$query="UPDATE #__joomleague_tip_members SET picture = '".$upload_class->file_name."' WHERE user_id = ".$my->id;
						$database->setQuery($query);
						$database->query();
							
						?>
		        <script type="text/javascript">
						// <![CDATA[
						<!--
						window.parent.document.getElementById('showFile').innerHTML = '<?php echo $picture;?>'; 
						window.parent.document.getElementById('picture').value = '<?php echo $upload_class->file_name;?>';
						window.parent.document.getElementById('delPicture').style.display = 'block';
						//-->
						// ]]>
						</script>
						<?php
		      }
		    }
		    // end of checking
		 
		    echo '<div style="font-family:Verdana;font-size:11px;">'.$result.'</div>';
		  }
		  else echo '<div style="font-family:Verdana;font-size:11px;">Not a valid user</div>';
		  break;
	
		case "showplayground":
			$mainframe->setPageTitle(_JL_ADMIN_VIEW_PLAYGROUNDS);
			//    $mainframe->appendPathWay(_JL_ADMIN_VIEW_PLAYGROUNDS);
		
			if ($pgid>0) {
				require JL_FUNCTIONS_PATH.'/showplayground.php';
				showPlayground($pgid, $overall_config);
			}
			break;
			
		case "editmatch":
			// used in ajax request
      // check edit rights
      if (   defined('JL_USER_IS_PROJECT_ADMIN') 
          || defined('JL_USER_IS_PROJECT_EDITOR') 
          || defined('JL_USER_IS_BIG_BOSS') 
          || $joomleague->isMatchAdmin( $mid, $my->id) )
      {
				$mytask=mosGetParam($_REQUEST, "mytask", '');
				$match = new Match($database);
			 	$match->load($mid);
			 	
				switch ($mytask) {
					case "cancel":
				  	$match->checkin( $mid );
						break;
					case "load":
					  $match->checkout( $my->id );
					  $team1 = new JL_Team($database);
					  $team1->load($match->matchpart1);
						$team2 = new JL_Team($database);
					  $team2->load($match->matchpart2);
					  $teams = $joomleague->getTeams();
					 	
		        // teams dropdown
		        foreach ($teams AS $team) {
					 		$teamsoptions[] = mosHTML::makeOption($team->id, $team->name);
						}
						
						// playground dropdown
		        if (intval($match->playground_id)<1) {
							$homteamtoolid=$joomleague->getTeamtool_id($match->matchpart1);
							$playgroundtt=new TeamTool($database);
							$playgroundtt->load($homteamtoolid);
							$selected_playground=$playgroundtt->standard_playground;
						}
						else $selected_playground=$match->playground_id;
						
						$playgrounds[] = mosHTML::makeOption( '0', jl_utf8_convert(_JL_ADMIN_SELECT_PLAYGROUND) );
						$query = "SELECT id AS value, name AS text FROM #__joomleague_playgrounds";
		        $database->setQuery($query);
		        
		        if ($temp = $database->loadObjectList()) foreach($temp AS $tmp) $tmp->text = jl_utf8_convert($tmp->text);
		        $playgrounds = array_merge( $playgrounds, $temp );
		        $playgroundslist = mosHTML::selectList( $playgrounds, 'playground_id'.$match->match_id, 'class="inputbox" style="font-size:9px;" size="1"','value', 'text', $selected_playground );
					  
		        // referees dropdown
					 	if ($joomleague->teams_as_referees)
						{
						  $query = "SELECT id, name FROM #__joomleague_teams ORDER BY name";
						  $database->setQuery($query);
						  $results = $database->loadObjectList();
						  $ref[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_REFEREE );
						  foreach($results as $result){
						   $ref[] = mosHTML::makeOption($result->id, jl_utf8_convert($result->name));
						  }
						}
						else
						{
						  $query = "SELECT id, firstname, lastname FROM #__joomleague_referees ORDER BY lastname";
						  $database->setQuery($query);
						  $results = $database->loadObjectList();
						  $ref[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_REFEREE );
						  foreach($results as $result){
						    $ref[] = mosHTML::makeOption($result->id, jl_utf8_convert("$result->lastname, $result->firstname"));
						  }
						}
						
		        //print_r($match);
					  $regular_output = false;
					  require JL_ADMIN_TEMPLATE_PATH.'/edit_match.tpl.php';
					  break;
				}
      }
	    break;
	    
		case "editevents":	
		  // check edit rights
			if (   defined('JL_USER_IS_PROJECT_ADMIN') 
			    || defined('JL_USER_IS_PROJECT_EDITOR') 
			    || defined('JL_USER_IS_BIG_BOSS') 
			    || $joomleague->isMatchAdmin( $mid, $my->id) )
		  {
		    $match = new Match($database);
		    $match->load($mid);
		    $regular_output = false;
				$mytask=mosGetParam($_REQUEST, "mytask",'');
				require JL_FUNCTIONS_PATH.'/editevents.class.php';
				$eved = new jl_EditEvents($joomleague, $match);
				
				switch($mytask) {
					case "editsquad":
						$eved->editSquad('block', 'block', 'none');
					  break;
					case "showevents":
					  $eved->showEvents('block');
					  break;
					case "saveevent":
			      $eved->saveMatchEvent();
			      $eved->showEvents('block');
					break;
					case "deleteevent":
						$eved->deleteMatchEvent();
						$eved->showEvents('block');
					break;
					case "updateevent":
					  $eved->updateMatchEvent();
					  $eved->showEvents('block');
						break;
					case "savesquads":
					  $eved->saveSquad();
					  $display_sq = 'block';
					  if (isset($_REQUEST['player_in'])) $display_sq = 'none';
					  $eved->editSquad('block', $display_sq, 'block');
					  break;
					  					  
          case "updatesubst":
            $eved->updateSubst();
            $display_sq = 'block';
            if (isset($_REQUEST['player_in'])) $display_sq = 'none';
            $eved->editSquad('block', $display_sq, 'block');
            break;
					
					default:
						$eved->showEventsNav();
				}
			}
			else echo "<span style='color:#ff0000;'><b>YOU ARE NOT ALLOWED!!!<br /></span>";
		  break;	
		  // Event Editing mode ends here
	  
		  case "eventsstats":
        $limitstart = 0;
        // specific event type to display. 0 for all events
        $eventtype = intval( mosGetParam($_REQUEST, 'evid', 0) );
        // number of rows to display
        $limit = intval( mosGetParam($_REQUEST, 'limit', 0) );
        // row start
        $limitstart = intval( mosGetParam($_REQUEST, 'limitstart', 0) );
        // layout config
        $events_config=$joomleague->getTemplateConfig("show_events_stats.tpl");
        // get project events types
        $eventtypes = $joomleague->getEventTypes($eventtype);
                
        // set number of rows to display
        if ( !$limit ) 
        {
          // depends on if we are displaying a unique event type, or all of them
          if ( $eventtype > 0 ) {
            if ( array_key_exists( 'max_events', $events_config )
              && intval( $events_config['max_events'] ) > 0 ) {
              $limit = $events_config['max_events'];
            }
            else {
              $limit = 20;
            }
          }
          else { // single event type
            $limit = ( isset($events_config['count_events']) ) ? $events_config['count_events'] : 5;
          }
        }
        
        // set page title
        $title=_JL_MODULE_NEXT_MATCH_STATISTIC." ";
        if ($eventtype>0) {
          $title .= $eventtypes[$eventtype]->name;
        }
        else {
          $title .= '- '._JL_SEF_EVENTS;
        }
        $mainframe->setPageTitle($title);
  
        // get ranking for each event types
        if (array_keys($eventtypes)) {
          foreach (array_keys($eventtypes) AS $eventkey) {
            $eventrankings[$eventkey] = $joomleague->getEventsRanking($eventkey, $eventtypes[$eventkey]->splitt, $eventtypes[$eventkey]->direction, $limit, $limitstart);
          }
        }
        require(getTemplateFile(JL_TEMPLATE_PATH, 'show_events_stats.tpl.php'));
        break;
	
	
	//##########################################################################################################################
	// Informationen zur Joomleague
	
	  case "about":
	  
	    $mainframe->setPageTitle(_JL_PAGE_TITLE_ABOUT);
	    
	    $v = new JoomLeagueVersion();
	
	
	    require(getTemplateFile(JL_TEMPLATE_PATH, 'about.tpl.php'));
	// Information Ende
	//##########################################################################################################################
	    
	  break;
	  
	
	  case 'showcurve_getchartdata':
	    
	    $division = intval(mosGetParam($_REQUEST, 'whatdivision', 0));
	    $team[$division]=intval(mosGetParam($_REQUEST, 'tid', 0));
	    $team2[$division]=intval(mosGetParam($_REQUEST, 'tid2', 0));
	    if ($team2[$division] == $team[$division]) $team2[$division] = 0;
	    $round=$joomleague->current_round;
	    $rounds = $joomleague->getRoundNames();
	  	$table_config=$joomleague->getTemplateConfig("show_table.tpl");
	  	$colors = $joomleague->getColors($table_config['colors']);
	  	$ranking = new Ranking();
	    $ranking->setProjectConfig($joomleague, $table_config['rankingorder']);
	    $platzierungen[$division]=array();
	  	$platzierungen2[$division]=array();
	  	$a[$division]=array();
	  	$teamcount = array();
	    for($x=1;$x<=$round;$x++)
	    {
		    $a[$division] = $ranking->getRanking(0, $x, 1, $table_config['show_negative_points'], $table_config['sort_table'], $division);
		    foreach ($a[$division] AS $key=>$value)
				{
					$platz=$value->rank;
					if ($team[$division]!=0 && $key == $team[$division]) $platzierungen[$division][]=($platz>0) ? $platz:'null';
					elseif ($team[$division]==0) $platzierungen[$division][]='null';
					if ($team2[$division]!=0 && $key == $team2[$division]) $platzierungen2[$division][]=($platz>0) ? $platz:'null';
					elseif ($team2[$division]==0) $platzierungen2[$division][]='null';
				}
			}
			$url_string=urldecode(str_replace("&amp;", "%26", JL_COMPONENT_LINK_NOHTML."%26divLevel=".$divLevel."%26func=showcurve_getchartdata%26p="
	    .$joomleague->id."%26".JL_ITEMID_SUFFIX));
		  require(getTemplateFile(JL_TEMPLATE_PATH, 'show_curve.tpl.php'));
	  break;
	  case "showcurve":
	    if ($joomleague->project_type == 'SIMPLE_KO') {
	      $url = sefRelToAbs(JL_COMPONENT_LINK.'&amp;func=showResults&amp;p='.$joomleague->id.JL_ITEMID_SUFFIX);
	      mosRedirect($url);
	    }
	    $favteams=explode(",", $joomleague->fav_team);
	    $team = array();
	    $team2 = array();
	
	    $table_config=$joomleague->getTemplateConfig("show_table.tpl");
	    $divLevel= $table_config['default_division_view'];
	    if ($joomleague->project_type=='DIVISIONS_LEAGUE') {
	      $selDivision = intval(mosGetParam($_REQUEST, 'division', 0));
	      if ( $divLevel ) $divisions = ($selDivision > 0) ? array($selDivision) : $joomleague->getDivisionsId( $divLevel );
	      else $divisions = array(0); //project
	      foreach ($divisions AS $division) {
	        $team[$division] = 0;
	        $team2[$division] = 0;
	        $allteams[$division] = $joomleague->getTeams(null, $division);
	      }
	    } 
	    else {
	      $divisions = array(0); //project
	      $allteams[0] = $joomleague->getTeams();
			   $selteam1 = (isset($favteams[0])) ? $favteams[0] : 0;
			   $selteam2 = (isset($favteams[1])) ? $favteams[1] : 0;
	  	  $team[0] = intval(mosGetParam($_REQUEST, 'tid', $selteam1));
	  	  $team2[0] = intval(mosGetParam($_REQUEST, 'tid2', $selteam2));
	  	}
	  	$height = array();
	  	$mainframe->setPageTitle(_JL_CURVE);
	  	$colors = $joomleague->getColors($table_config['colors']);
	  	foreach ($allteams AS $key => $value) {
	  	  $selectoptions[$key][]= mosHTML::makeOption(0, _JL_CHOOSE_TEAM);
	      $teamlist2options[$key][]= mosHTML::makeOption(0, _JL_CHOOSE_TEAM);
	  	  foreach ($value AS $divisionteams){
	  	  if ($team[$key] == 0) $team[$key]=intval(mosGetParam($_REQUEST, 'tid', 0));
	  	  if ($team2[$key] == 0) $team2[$key]=intval(mosGetParam($_REQUEST, 'tid2', 0));
	  	  if ($team[$key] == 0 && in_array($divisionteams->team_id, $favteams)) $team[$key] = $divisionteams->team_id;
				if ($team2[$key] == 0 && in_array($divisionteams->team_id, $favteams) && $divisionteams->team_id != $team[$key]) $team2[$key] = $divisionteams->team_id;
	        $selectoptions[$key][]= mosHTML::makeOption($divisionteams->team_id, $divisionteams->name);
	        $teamlist2options[$key][]= mosHTML::makeOption($divisionteams->team_id, $divisionteams->name);
	      }
	      $teamcount[$key] = count($value);
			  $tempheight = 20 * $teamcount[$key];
			  $height[$key] = ($tempheight > 180) ? $tempheight : 180;
	  	}
	    $url_string=urldecode(str_replace("&amp;", "%26", JL_COMPONENT_LINK_NOHTML."%26divLevel=".$divLevel."%26func=showcurve_getchartdata%26p="
	    .$joomleague->id.JL_ITEMID_SUFFIX));
		  require(getTemplateFile(JL_TEMPLATE_PATH, 'show_curve.tpl.php'));
	  break;
	  
	//##########################################################################################################################
	// Tabelle anzeigen
	  
	  case "showranking":
	  
	  $mainframe->setPageTitle(_JL_PAGE_TITLE_RANKING);
	//  $mainframe->appendPathWay(_JL_PAGE_TITLE_RANKING);
	  require JL_FUNCTIONS_PATH.'/showranking.php';
	  showRanking($jl_func, $r, $overall_config);
	
	  break;
	
	//##########################################################################################################################
	  
	// Kombi begins
	  case "showresultsrank":
	    require JL_FUNCTIONS_PATH.'/showresultsranking.php';
	    require JL_FUNCTIONS_PATH.'/showresults.php';
	    require JL_FUNCTIONS_PATH.'/showranking.php';
	    showResultsRanking( $jl_func, $r, $overall_config );
	  break;
	  
	//##########################################################################################################################
	// Spielplan anzeigen
	  case "showplan":
	  
	    $mainframe->setPageTitle(_JL_PAGE_TITLE_PLAN);
	//    $mainframe->appendPathWay(_JL_PAGE_TITLE_PLAN);
	    require JL_FUNCTIONS_PATH.'/showplan.php';
	    showPlan($jl_func, $tid, $overall_config);
	   
	  break;
	//##########################################################################################################################
	// Anzeige der Ergebnisse  
	  case "editresults":
	    $htmlHelper->makeAjaxContainer ('evedit', 'myeventscontainer');
	    require JL_FUNCTIONS_PATH.'/editresults.php';
	    editResults($jl_func, $r, $overall_config);
	
	  break;
	  
	  case "showresults":
	  
	  require JL_FUNCTIONS_PATH.'/showresults.php';
	  showResults ($jl_func, $r, $overall_config);
	  
	  break;
	
	    
	// Ergebnisanzeige Ende
	//##########################################################################################################################
	    
	  case "shownextmatch":
	
	    $showNextMatch_config=$joomleague->getTemplateConfig("show_next_match.tpl");    
	    $table_config=$joomleague->getTemplateConfig("show_table.tpl");
	    if($mid > 0){
	      $match = new Match($database);
	      $match->load($mid);
	      
	      $project_id = $match->project_id;
	      $joomleague = new JoomLeague($database);
	      $joomleague->load($project_id);
	    }
	    $show_pics = mosGetParam($_REQUEST, 'pics', "0");
	    $mainframe->setPageTitle(_JL_PAGE_TITLE_NEXT_MATCH);
	//    $mainframe->appendPathWay(_JL_PAGE_TITLE_NEXT_MATCH);
	    $team1 = new JL_Team($database);
	    $team1->load($match->matchpart1);
	    
	    $team2 = new JL_Team($database);
	    $team2->load($match->matchpart2);
	    
	    $teams[] = $team1;
	    $teams[] = $team2;
	    
	    # so, we have the match, get the images from clubs
	    $query = sprintf("SELECT logo_big FROM #__joomleague_clubs clubs
	                   LEFT JOIN #__joomleague_teams teams ON clubs.id = teams.club_id
	                       WHERE teams.id = %s", $match->matchpart1);
	    $database->setQuery($query);
	    $matchpart1_pic = $database->loadResult();
	    
	    $query = sprintf("SELECT logo_big FROM #__joomleague_clubs clubs
	                   LEFT JOIN #__joomleague_teams teams ON clubs.id = teams.club_id
	                       WHERE teams.id = %s", $match->matchpart2);
	    $database->setQuery($query);
	    $matchpart2_pic = $database->loadResult();
	
	    $matchpart_pics[] = (trim($matchpart1_pic) != "")? sprintf('<img src="%s/%s" alt="%s" title="%s"/>', _JOOMLA_JL_LIVE_SITE, $matchpart1_pic, $teams[0]->name, $teams[0]->name) : "&nbsp;";
	    $matchpart_pics[] = (trim($matchpart2_pic) != "")? sprintf('<img src="%s/%s" alt="%s" title="%s"/>', _JOOMLA_JL_LIVE_SITE, $matchpart2_pic, $teams[1]->name, $teams[1]->name) : "&nbsp;";
	    
	    
	    
	    $ranking = new Ranking();
	    $ranking->setProjectConfig($joomleague, $table_config['rankingorder']);
	    
	    $a = $ranking->getRanking(0, $joomleague->current_round + 1, 1, $table_config['show_negative_points'], $table_config['sort_table']);
	    $homeRanked = $a[$teams[0]->id];
	    $awayRanked = $a[$teams[1]->id];
	    
	    $round=$joomleague->current_round + 1;
	
	    // biggest hometeam home win
		  $query="SELECT t1.name AS hometeam, t2.name AS awayteam,
		                     matchpart1_result AS homegoals,
		                     matchpart2_result AS awaygoals
		                     FROM #__joomleague_matches as matches
		                     LEFT JOIN #__joomleague_teams t1
		                     ON t1.id = matches.matchpart1
		                     LEFT JOIN #__joomleague_teams t2
		                     ON t2.id = matches.matchpart2
		                     WHERE project_id = $project_id AND published=1 AND alt_decision=0
		                     AND t1.id=$team1->id
		                     ORDER BY (matchpart1_result-matchpart2_result) DESC
		                     LIMIT 0,1";
	    $database->setQuery($query);
	    $home_highest_home_win = NULL;
	    if ( !$database->loadObject($home_highest_home_win) ) print_r($database->getErrorMsg());
	    
	    // biggest awayteam home win
	    $query="SELECT t1.name AS hometeam, t2.name AS awayteam,
	                       matchpart1_result AS homegoals,
	                       matchpart2_result AS awaygoals
	                       FROM #__joomleague_matches as matches
	                       LEFT JOIN #__joomleague_teams t1
	                       ON t1.id = matches.matchpart1
	                       LEFT JOIN #__joomleague_teams t2
	                       ON t2.id = matches.matchpart2
	                       WHERE project_id = $project_id AND published=1 AND alt_decision=0
	                       AND t1.id=$team2->id
	                       ORDER BY (matchpart1_result-matchpart2_result) DESC
	                       LIMIT 0,1";
	    $database->setQuery($query);
	    $away_highest_home_win = NULL;
	    if ( !$database->loadObject($away_highest_home_win) ) print_r($database->getErrorMsg());
	    
	    // biggest hometeam home defeat
	    $query="SELECT t1.name AS hometeam, t2.name AS awayteam,
	                       matchpart1_result AS homegoals,
	                       matchpart2_result AS awaygoals
	                       FROM #__joomleague_matches as matches
	                       LEFT JOIN #__joomleague_teams t1
	                       ON t1.id = matches.matchpart1
	                       LEFT JOIN #__joomleague_teams t2
	                       ON t2.id = matches.matchpart2
	                       WHERE project_id = $project_id AND published=1 AND alt_decision=0
	                       AND t1.id=$team1->id
	                       ORDER BY (matchpart2_result-matchpart1_result) DESC
	                       LIMIT 0,1";
	    $database->setQuery($query);
	    $home_highest_home_def = NULL;
	    if ( !$database->loadObject($home_highest_home_def) ) print_r($database->getErrorMsg());
	    
	    // biggest awayteam home defeat
	    $query="SELECT t1.name AS hometeam, t2.name AS awayteam,
	                       matchpart1_result AS homegoals,
	                       matchpart2_result AS awaygoals
	                       FROM #__joomleague_matches as matches
	                       LEFT JOIN #__joomleague_teams t1
	                       ON t1.id = matches.matchpart1
	                       LEFT JOIN #__joomleague_teams t2
	                       ON t2.id = matches.matchpart2
	                       WHERE project_id = $project_id AND published=1 AND alt_decision=0
	                       AND t1.id=$team2->id
	                       ORDER BY (matchpart2_result-matchpart1_result) DESC
	                       LIMIT 0,1";
	    $database->setQuery($query);
	    $away_highest_home_def = NULL;
	    if ( !$database->loadObject($away_highest_home_def) ) print_r($database->getErrorMsg());
	    
	    // biggest hometeam away defeat
	    $query="SELECT t1.name AS hometeam, t2.name AS awayteam,
	                       matchpart1_result AS homegoals,
	                       matchpart2_result AS awaygoals
	                       FROM #__joomleague_matches as matches
	                       LEFT JOIN #__joomleague_teams t1
	                       ON t1.id = matches.matchpart1
	                       LEFT JOIN #__joomleague_teams t2
	                       ON t2.id = matches.matchpart2
	                       WHERE project_id = $project_id AND published=1 AND alt_decision=0
	                       AND t2.id=$team1->id
	                       ORDER BY (matchpart1_result-matchpart2_result) DESC
	                       LIMIT 0,1";
	    $database->setQuery($query);
	    $home_highest_away_def = NULL;
	    if ( !$database->loadObject($home_highest_away_def) ) print_r($database->getErrorMsg());
	    
	    // biggest awayteam away defeat
	    $query="SELECT t1.name AS hometeam, t2.name AS awayteam,
	                       matchpart1_result AS homegoals,
	                       matchpart2_result AS awaygoals
	                       FROM #__joomleague_matches as matches
	                       LEFT JOIN #__joomleague_teams t1
	                       ON t1.id = matches.matchpart1
	                       LEFT JOIN #__joomleague_teams t2
	                       ON t2.id = matches.matchpart2
	                       WHERE project_id = $project_id AND published=1 AND alt_decision=0
	                       AND t2.id=$team2->id
	                       ORDER BY (matchpart1_result-matchpart2_result) DESC
	                       LIMIT 0,1";
	    $database->setQuery($query);
	    $away_highest_away_def = NULL;
	    if ( !$database->loadObject($away_highest_away_def) ) print_r($database->getErrorMsg());
	    
	    // biggest hometeam away won
	    $query="SELECT t1.name AS hometeam, t2.name AS awayteam,
	                       matchpart1_result AS homegoals,
	                       matchpart2_result AS awaygoals
	                       FROM #__joomleague_matches as matches
	                       LEFT JOIN #__joomleague_teams t1
	                       ON t1.id = matches.matchpart1
	                       LEFT JOIN #__joomleague_teams t2
	                       ON t2.id = matches.matchpart2
	                       WHERE project_id = $project_id AND published=1 AND alt_decision=0
	                       AND t2.id=$team1->id
	                       ORDER BY (matchpart2_result-matchpart1_result) DESC
	                       LIMIT 0,1";
	    $database->setQuery($query);
	    $home_highest_away_win = NULL;
	    if ( !$database->loadObject($home_highest_away_win) ) print_r($database->getErrorMsg());
	    
	    // biggest awayteam away won
	    $query="SELECT t1.name AS hometeam, t2.name AS awayteam,
	                       matchpart1_result AS homegoals,
	                       matchpart2_result AS awaygoals
	                       FROM #__joomleague_matches as matches
	                       LEFT JOIN #__joomleague_teams t1
	                       ON t1.id = matches.matchpart1
	                       LEFT JOIN #__joomleague_teams t2
	                       ON t2.id = matches.matchpart2
	                       WHERE project_id = $project_id AND published=1 AND alt_decision=0
	                       AND t2.id=$team2->id
	                       ORDER BY (matchpart2_result-matchpart1_result) DESC
	                       LIMIT 0,1";
	    $database->setQuery($query);
	    $away_highest_away_win = NULL;
	    if ( !$database->loadObject($away_highest_away_win) ) print_r($database->getErrorMsg());
	    
	    require(getTemplateFile(JL_TEMPLATE_PATH, 'show_next_match.tpl.php'));
	    
	// Anzeige des n�chsten Spiels Ende
	//##########################################################################################################################
	    
	  break;
	 
	//##########################################################################################################################
	
	   
	  case "saveresults":
	  $msid = mosGetParam($_POST, 'msid', '');
	  $allowed=0;
	  // has to be in a function with configuration of alloweds in backend...later...i'm tired now
	  if(  defined('JL_USER_IS_PROJECT_ADMIN')
	    || defined('JL_USER_IS_PROJECT_EDITOR') 
	    || defined('JL_USER_IS_BIG_BOSS') ) {
	  	$allowed=1;
	  }
	  
	  foreach($msid as $cids) {
	  	$savedata=intval(mosGetParam($_POST, 'save_data', 0));
	  	
	  	if ( $allowed==1 || $joomleague->isMatchAdmin( $cids, $my->id ) ) {
				$match = new Match( $database );
				$match->load($cids);
				if ($savedata==1) {
				  foreach ($_POST AS $key => $value) {
				    if (substr($key, 0, 7) == 'summary') $resultsave[$key] = mosGetParam($_POST, "$key", '', _MOS_ALLOWHTML);
	          else $resultsave[$key] = mosGetParam($_POST, "$key", '');
	//          echo substr($key, 0, 7).'<br />';
	        }
				  $match->save_array($cids,$resultsave,true,$joomleague->id);
				}
				$match->checkin($cids);
			}
		}
	    if ($allowed==1 && $joomleague->current_round_auto==0) {
	    	$set_round=mosGetParam($_POST, 'set_r', '');
		    $query="UPDATE #__joomleague SET current_round = '$set_round' where id = ".$joomleague->id;
		    $database->setQuery($query);
		    $result = $database->query();
		  }
	    $sel_round = mosGetParam($_POST, 'sel_r', '');
	    mosRedirect(JL_COMPONENT_LINK.'&amp;func=editResults&amp;p='
	                .$joomleague->id.'&amp;r='.$sel_round.JL_ITEMID_SUFFIX);
	    
	// Ergebnisse speichern Ende
	//##########################################################################################################################
	    
	  break;
	// Matrix aller Spiel zeigen (funktioniert nicht richtig)
	  
	  case "showmatrix":
	    require JL_FUNCTIONS_PATH.'/showmatrix.php';
	    showMatrix();
	    break;
	
	  //##########################################################################################################################
	// Hier werden die Spielberichte angezeigt
	  
	  case "showreport":
	  if ($mid > 0){
	  require JL_FUNCTIONS_PATH.'/showreport.php';
	  showReport ($mid, $joomleague);
	  }
	      
	// Spielberichte Ende
	//##########################################################################################################################
	  break;
	
	//##########################################################################################################################
	// Informationen �ber die Vereine bzw. Clubs anzeigen new case 2007/03/04, fullfilled on 15.5.7 by JST
	  
	  case "showteaminfo":
      require JL_FUNCTIONS_PATH.'/showteaminfo.php';
      showteaminfo( $overall_config );
	    break;
	    
	  case "showclubinfo":
	  
	    require JL_FUNCTIONS_PATH.'/showclub.php';
	    showClubInfo( $cid ,$overall_config); 
	       
	    break;
	    
	  case "editclubinfo":
	  
	    switch ($task = mosGetParam($_REQUEST , 'task' , '')) { 
	      
	      case 'save':
	        if($cid > 0){
	          $club = new Club($database);
	          $club->load($cid);
	          $club->bind($_POST);
	          
	          if ($club->store() && $jlgConfig['club_info_update_notify']=="1") {
	            // $jlconfig_club_info_update_notify should be defined in a config file later.
	            // retrieve admin emails
	            $database->setQuery( "SELECT email FROM #__users WHERE usertype = 'Super Administrator' OR usertype = 'Administrator'" );
	            $to = $database->loadResultArray();
	            
	            $subject = sprintf( '[' . $mainframe->getCfg( 'sitename' ) . '] ' . _JL_CLUB_EDIT_EMAIL_NOTICE_TITLE, $club->name );
	            $message = sprintf( _JL_CLUB_EDIT_EMAIL_NOTICE_BODY, $my->name, $club->name );
	            $message .= JLLIVEURL.sprintf("/index.php?option=com_joomleague&func=showclubinfo&cid=%s&p=%s",mosGetParam($_REQUEST , 'cid' , ''), mosGetParam($_REQUEST , 'p' , ''));
	            
	            mosMail('', '', $to, $subject, $message);
	          }
	        }
	        mosRedirect(sprintf("index.php?option=com_joomleague&func=showclubinfo&cid=%s&p=%s",mosGetParam($_REQUEST , 'cid' , ''), mosGetParam($_REQUEST , 'p' , '')));
	      case 'cancel':
	        mosRedirect(sprintf("index.php?option=com_joomleague&func=showclubinfo&cid=%s&p=%s",mosGetParam($_REQUEST , 'cid' , ''), mosGetParam($_REQUEST , 'p' , '')));
	
	      default:
	        $showClub_config=$joomleague->getTemplateConfig("show_club.tpl");
	        
	        $mainframe->setPageTitle(_JL_PAGE_TITLE_CLUB_INFO);
	    //    $mainframe->appendPathWay(_JL_PAGE_TITLE_CLUB_INFO);
	        if($cid > 0){
	          $club = new Club($database);
	          $club->load($cid);
	              
	        // now get all teams which belongs to this club (TODO: check published state of projects/seasons!!)
	        $query = sprintf("SELECT id, name as team_name, short_name as team_shortcut, description as team_description 
	                            FROM #__joomleague_teams
	                           WHERE club_id = %s", $cid);
	        
	        $database->setQuery($query);
	        // TODO: put result with this project ID first!!
	        $rows = $database->loadObjectList();
	    		if (count($rows>0)) {
	    			foreach ($rows AS $row) {
	    				$query="SELECT distinct(standard_playground) FROM #__joomleague_team_joomleague
	    				WHERE team_id = $row->id";
	    				$database->setQuery($query);
	    				$stadiums[] = $database->loadObjectList();
	    			}
	    		}
	    		
	    		//build countries select list
	    		$selectedvalue=$club->country;
	    		$countrycode=explode("_", _JL_LOCALE);
	        $countries[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_COUNTRY );
	        $database->setQuery( "SELECT countries_id, countries_name, countries_iso_code_2, countries_iso_code_3, countries_localname FROM #__joomleague_countries WHERE published = 1");
	        $results = $database->loadObjectList();
	        
	        foreach ($results AS $result) {
	        	if ( strtoupper($result->countries_iso_code_2) == strtoupper($countrycode[0]) ) {
	        		if (is_null($club->country)) $selectedvalue=$result->countries_id;
	        		$value=$result->countries_localname;
	        	}
	        	else {
	        		if (isset($country[$result->countries_iso_code_3])) $value=$country[$result->countries_iso_code_3];
	        		else $value=$result->countries_name;
	        	}
	        	$countries[] = mosHTML::makeOption( $result->countries_id, "$value" );
					}
	        $clist = mosHTML::selectList( $countries, 'country', 'class="inputbox" size="1"','value', 'text', $selectedvalue );
	        if (is_null($club->country)) $clist.="<b>"._JL_ADMIN_NOT_USED."</b>";
	        unset($countries);
	        
	    		//editors      
	        if(defined('JL_USER_IS_BIG_BOSS')
	            || ($my->id > 0 && $my->id == $club->admin) ) 
	        {            	
	          $allowed=1;
	          
					  // select list of images from placeholder folder
					  $images[] = mosHTML::makeOption( '', _JL_ADMIN_SELECT_PICTURE );
					  if ( $dp = opendir( _JOOMLA_JL_PATH . '/images/joomleague/placeholders' ) )
					  {
					    $list = array();
					    while ( ( $file = readdir( $dp ) ) !== false )
					    {
					      if (preg_match('#^[^&\'"<>]+\.(?:gif|png|jpe?g)$#i', $file ) ) {
					        $list[] = $file;
					      }
					    }
					    if ( count($list) ) 
					    {
					      sort( $list );
					      foreach ($list as $l) {
					        $images[] = mosHTML::makeOption( '/images/joomleague/placeholders/'.$l, $l );
					      }
					    }
					    closedir($dp);
					  }
					  $logo_big_list = mosHTML::selectList( $images, 'logo_big', 'class="inputbox" size="1"','value', 'text', $club->logo_big );
					  $logo_middle_list = mosHTML::selectList( $images, 'logo_middle', 'class="inputbox" size="1"','value', 'text', $club->logo_middle );
					  $logo_small_list = mosHTML::selectList( $images, 'logo_small', 'class="inputbox" size="1"','value', 'text', $club->logo_small );
					  unset( $images );
	  
	          require(getTemplateFile(JL_TEMPLATE_PATH, 'edit_club_info.tpl.php'));
	        }
	    		
	        }
	        break;
	    }
	    break;
	    
	//##########################################################################################################################
	//##########################################################################################################################
	// Anzeige des Mannschaftskaders
	
	  case "showplayers":
	  
			$showPlayers_config=$joomleague->getTemplateConfig("show_players.tpl");
	    
	    if(is_a($teamtool,'Teamtool')){
	      $team = new JL_Team( $database );
	      $team->load($teamtool->team_id);
	      $mainframe->setPageTitle(_JL_PAGE_TITLE_PLAYERS.' - '.$team->name);
	//    $mainframe->appendPathWay(_JL_PAGE_TITLE_PLAYERS.' - '.$team->name);
	      #list players of a team
	      $query = "SELECT pt.*, p.*, p.id AS pid, pos.name as position
	                          FROM #__joomleague_playertool pt
	                          INNER JOIN #__joomleague_players p ON pt.player_id = p.id
	                          INNER JOIN #__joomleague_positions pos ON pos.id = pt.position_id
	                          WHERE pt.team_id = '$team->id' AND
	                          pt.project_id = '$teamtool->project_id'
	                          ORDER BY pos.ordering, pt.position_id, pt.position_number";
	      $database->setQuery($query);
	      $rows = $database->loadObjectList();
	      //print_r($rows); exit;
	
	    	if ($showPlayers_config['show_stats']==1&&count($rows)>0) {
					$PosEventtypes=$joomleague->getPositionEventTypes();
	      	foreach ($rows AS $row) {
	      		$playerEvents[$row->id] = array();
	      		if ( isset($PosEventtypes[$row->position_id]) ) {
		      		foreach ($PosEventtypes[$row->position_id] as $event) {      				
		      			$playerStats[$row->id][$event->eventtype_id] = $joomleague->getPlayerEvents($row->player_id, $event->eventtype_id, $row->team_id);
		      		}
	      		}
	    		}
	    		//print_r($playerStats);exit;
				}
				
			  $query = sprintf("SELECT p.*, pos.name as position, ts.picture, teamstaff_id
	                          FROM #__joomleague_teamstaff_project ts
	                          INNER JOIN #__joomleague_players p ON ts.person_id = p.id
	                          INNER JOIN #__joomleague_positions pos ON pos.id = ts.position_id
	                          WHERE projectteam_id= '%s'     
	                      	  ORDER BY pos.ordering, ts.position_id
	                      ", $teamtool->id);
	      $database->setQuery($query);
	      $stafflist = $database->loadObjectList();		
		 
	// new for events in team-info Gucky 2007/05/28 END
	
	      require(getTemplateFile(JL_TEMPLATE_PATH, 'show_players.tpl.php'));
	    }
	    else print "no data!";   
	  
	
	  break;    
	//##########################################################################################################################
	// Spieleranzeige  
	  
	  
	  case "showplayer":
	    // pid is player id not playertool id
	    $showPlayer_config=$joomleague->getTemplateConfig("show_player.tpl");
	    if($pid > 0) {
	      $history = jl_getPlayerHistory($pid, 'DESC');
	      $historyStaff = jl_getStaffHistory ($pid, 'DESC');
	      
	      $query = "SELECT p.*, p.description as pdescription,
	                       pt.id AS playertoolid, pt.description as ptdescription, pt.*, 
	                       pp.name as position, pp.isStaff, 
	                       proj.name as proj_name, 
	                       t.name as team_name
	                FROM #__joomleague_playertool pt
	                INNER JOIN #__joomleague_team_joomleague tt ON (pt.team_id = tt.team_id AND tt.project_id=pt.project_id) 
	                INNER JOIN #__joomleague_players p ON p.id = pt.player_id
	                INNER JOIN #__joomleague_teams AS t ON t.id = pt.team_id
	                INNER JOIN #__joomleague_positions pp ON pp.id = pt.position_id
	                INNER JOIN #__joomleague AS proj ON pt.project_id = proj.id
	                INNER JOIN #__joomleague_seasons AS s ON s.id = proj.season_id
	                INNER JOIN #__joomleague_leagues AS l ON l.id = proj.league_id
	                WHERE p.id = $pid AND proj.published=1
	                ORDER BY s.ordering DESC, l.ordering DESC, proj.name ASC";
	      
	      $database->setQuery($query);
	      $rows = $database->loadObjectList('project_id');
	     
	      if(count($rows) > 0){
	      	//       	
	        $row=&$rows[$joomleague->id];
	        $rows = $database->loadObjectList();
	        $eventtypes = $joomleague->getPositionEventTypes($row->position_id);
	        // get contact_id if needed
		      if ( $showPlayer_config['show_user_profile'] == 1 && $row->jl_user_id ) {
		           $query = "SELECT id FROM #__contact_details WHERE user_id = $row->jl_user_id AND catid=".$showPlayer_config['contact_cat_id'];
		           $database->setQuery($query);
		           if (!$contact_id = $database->loadResult()) {
		             //echo $database->getQuery();
		           }
		      }
	
	//        $database->setQuery($query);
	        
	        $mainframe->setPageTitle(_JL_PAGE_TITLE_PLAYER.' - '.$row->firstname.' '.$row->lastname);
	        require(getTemplateFile(JL_TEMPLATE_PATH, 'show_player.tpl.php'));
	      }
	      else print "no data";
	    }
	  break;
	  
	//##########################################################################################################################
	// Teamstaff Display  
	  
	  case "showteamstaff":
	    // teamstaff id
	    $tsid = intval( mosGetParam($_REQUEST, 'tsid',0) );
	    
	    $showPlayer_config=$joomleague->getTemplateConfig("show_player.tpl");
	    if($pid > 0){
		  $teamstaff = new TeamStaff($database);
	      $teamstaff->load($pid);
	      $history = jl_getPlayerHistory($pid, 'DESC');
	      $historyStaff = jl_getStaffHistory ($pid, 'DESC');
	    }
	    
	//    $mainframe->appendPathWay(_JL_PAGE_TITLE_PLAYER);
	    if(is_a($teamstaff,'TeamStaff')){
		  $teamtool = new Teamtool ($database);
		  $teamtool->load($teamstaff->projectteam_id);
	      $team = new JL_Team( $database );
	      $team->load($teamtool->team_id);
	      
	      $query = ' SELECT p.*, pp.name as position, ts.picture, ts.description '
	      				. ' FROM #__joomleague_teamstaff_project AS ts '
	      				. ' INNER JOIN #__joomleague_players AS p ON p.id = ts.person_id '
	      				. ' LEFT JOIN #__joomleague_positions AS pp ON pp.id = ts.position_id '
	      				. ' WHERE ts.teamstaff_id = ' . $tsid; 
	      
	      $database->setQuery($query);
	      $rows = $database->loadObjectList();
	     
	      if(count($rows) > 0){
	        $row=&$rows[0];
	        $mainframe->setPageTitle(_JL_PAGE_TITLE_PLAYER.' - '.$row->firstname.' '.$row->lastname);
	        require(getTemplateFile(JL_TEMPLATE_PATH, 'show_teamstaff.tpl.php'));
	      }
	      else {
	      print "no data";
	      }
	    }
	  break;
	
	  default:
	    if(isset($error) && $error != null) print $error->getError();
	  break;
	  
	  case "showstats":
	  case "showstats_getchartdata":
	  	  $p = $joomleague->id;
	      $showStats_config = $joomleague->getTemplateConfig( "show_stats.tpl" );
	      $table_config = $joomleague->getTemplateConfig( "show_table.tpl" );
	      
	      if ($showStats_config['show_events_stats'] == "1") {
	        $events_config = $joomleague->getTemplateConfig("show_events_stats.tpl");
	      }
	      $mainframe->setPageTitle( _JL_PAGE_SEASON_STATS . " - " .$joomleague->name );
	      
	      $actualround=$joomleague->current_round;
	      
	      $query="SELECT t1.name AS hometeam, t2.name AS guestteam,
	                     matchpart1_result AS homegoals,
	                     matchpart2_result AS guestgoals
								       FROM #__joomleague_matches as matches
								       LEFT JOIN #__joomleague_teams t1
	                     ON t1.id = matches.matchpart1
	                     LEFT JOIN #__joomleague_teams t2
	                     ON t2.id = matches.matchpart2
								       WHERE project_id = $p AND published=1 AND alt_decision=0
								       ORDER BY (matchpart1_result-matchpart2_result) DESC
								       LIMIT 0,1";
	      $database->setQuery($query);
	      $highest_home = NULL;
	      if ( !$database->loadObject($highest_home) ) print_r($database->getErrorMsg());
	      
	      $query="SELECT t1.name AS hometeam, t2.name AS guestteam,
	                     matchpart1_result AS homegoals,
	                     matchpart2_result AS guestgoals
	                     FROM #__joomleague_matches as matches
	                     LEFT JOIN #__joomleague_teams t1
	                     ON t1.id = matches.matchpart1
	                     LEFT JOIN #__joomleague_teams t2
	                     ON t2.id = matches.matchpart2
	                     WHERE project_id = $p AND published=1 AND alt_decision=0
	                     ORDER BY (matchpart2_result-matchpart1_result) DESC
	                     LIMIT 0,1";
	      $database->setQuery($query);
	      $highest_away = NULL;
	      if ( !$database->loadObject($highest_away) ) print_r($database->getErrorMsg());
	
	      // global sums
	      $query="SELECT count(match_id) AS totalmatches,
	        count(matchpart1_result) AS playedmatches,
	        SUM(matchpart1_result) AS homegoals,
	        SUM(matchpart2_result) AS guestgoals,
	        (SUM(matchpart1_result)+SUM(matchpart2_result)) AS sumgoals,
	        count(crowd) AS attendedmatches,
	        sum(crowd) AS sumspectators
	        FROM #__joomleague_matches
	        WHERE project_id = $p AND published=1";
	      $database->setQuery($query);
	      $totals = $database->loadObjectList();
	
	      // matchday sums
	      $query="SELECT rounds.id, 
	          count(matches.match_id) AS totalmatchespd,
	        count(matches.matchpart1_result) as playedmatchespd,
	        SUM(matches.matchpart1_result) AS homegoalspd,
	        SUM(matches.matchpart2_result) AS guestgoalspd,
	        rounds.matchcode
	        FROM #__joomleague_rounds rounds
	        LEFT JOIN #__joomleague_matches matches
	        ON rounds.id = matches.round_id
	        WHERE rounds.project_id = $p
	        GROUP BY rounds.matchcode
	        ";
	      $database->setQuery($query);
	      $rows = $database->loadObjectList();
	      
	      // get rounds count
	      $query="SELECT count(id) FROM #__joomleague_rounds WHERE project_id=$joomleague->id";
	      $database->setQuery($query);
	      $totalrounds=$database->loadResult();
	      
	      //attendance per team
	      $query="SELECT sum(matches.crowd) AS sumspectatorspt,
		      avg(matches.crowd) AS avgspectatorspt,
		      teams.name AS team,
		      teams.id AS teamid,
		      playground.max_visitors AS capacity
		      FROM #__joomleague_matches AS matches
		      LEFT JOIN #__joomleague_teams AS teams ON matches.matchpart1 = teams.id
		      LEFT JOIN (#__joomleague_team_joomleague AS teamtool
		                 LEFT JOIN #__joomleague_playgrounds AS playground ON teamtool.standard_playground = playground.id)
		      ON matches.matchpart1 = teamtool.team_id AND matches.project_id = teamtool.project_id
		      WHERE matches.project_id = $p AND matches.published=1 AND matches.crowd IS NOT NULL
		      GROUP BY matches.matchpart1
		      ORDER BY avgspectatorspt DESC";
	      $database->setQuery($query);
	      $attendance_ranking = $database->loadObjectList();
	      
	      if (count($attendance_ranking)) {
		      $n = count($attendance_ranking)-1;
		      $bestavg = round($attendance_ranking[0]->avgspectatorspt);
		      $bestavgteam = $attendance_ranking[0]->team;
		      $worstavg = round($attendance_ranking[$n]->avgspectatorspt);
		      $worstavgteam = $attendance_ranking[$n]->team;
	      }
	      
	      if ( $showStats_config['show_events_stats'] )
	      {
		      // get players ranking per event
		      $eventtypes=array();
		      $limit=3;
		      $eventtypes = $joomleague->getEventTypes();
		
		      if (array_keys($eventtypes)) 
		      {
		        foreach (array_keys($eventtypes) AS $eventkey) {
		          $eventrankings[$eventkey] = $joomleague->getEventsRanking($eventkey, $eventtypes[$eventkey]->splitt, $eventtypes[$eventkey]->direction, 5, 0);
		        }
		      }
	      }	      
	      require(getTemplateFile(JL_TEMPLATE_PATH, 'show_stats.tpl.php'));
	    
	    break;
	//##########################################################################################################################
	
	// Prediction game starts
	//##########################################################################################################################
	//Start des Tippbereiches  
	//##########################################################################################################################
	// Start der Benachrichtgungsfunktion (funktionert momentan nicht)  
	  
	  case "requestnotification":
	    
	    if($my->id){
	      
	      $uid = intval(mosGetParam($_POST, 'notify_value', 0));
	      if($uid == $my->id){
	        
	        $members = (trim($joomleague->notify_to) != "")? explode("|",$joomleague->notify_to) : array();
	        
	        if(isset($_POST["notify_me"])){
	          //notfiy me
	          array_push($members, $my->id);          
	          $members = array_flip(array_flip($members));
	        }
	        else{
	          // dont notify me anylonger
	          $members = array_flip($members);
	          unset($members["$my->id"]);
	          $members = array_flip($members);
	        }
	        
	        $query = sprintf("UPDATE #__joomleague SET notify_to = '%s' WHERE id = %s", implode("|",$members), $joomleague->id);
	        $database->setQuery($query);
	        $database->query();
	      }
	      
	    }
	    
	    
	    $round = ($r == 0) ? $joomleague->current_round : $r;
	    mosRedirect(sprintf(JL_COMPONENT_LINK."&func=showResults&p=%s&r=%s".JL_ITEMID_SUFFIX,$joomleague->id, $round));
	
	// Benachrichtgungsfunktion Ende
	//##########################################################################################################################
	    
	  break;
	  
	  //##########################################################################################################################
	// Tippspiel Benutzer Profil
	
	  case "showuser":
	  case "showuser_getchartdatascore":
	  case "showuser_getchartdatarank":
	  if ( defined('JL_PREDICTION') && TRUE===JL_PREDICTION ){
	    $joomleague->getPredictionConfig();
	    $showUser_config=$joomleague->getTemplateConfig("show_user.tpl");
	    $doTips_config=$joomleague->getTemplateConfig("do_tips.tpl");
	    $showTipRanking_config=$joomleague->getTemplateConfig("show_tip_ranking.tpl");
	    $table_config=$joomleague->getTemplateConfig("show_table.tpl");
	    $mainframe->setPageTitle(_JL_USER_PAGE);
	    if (((!isset($_GET['uid']))||($uid==''))&&$my->id>0) $uid = $my->id; else if ((!isset($_GET['uid']))||($uid=='')) $uid = 0;
	    $mytask = mosGetParam($_REQUEST, 'mytask', '');
	    $allowed=0;
	    if(($my->id == $uid) && ($my->id > 0)) {
	      $allowed=1;
	    }
	    require (JL_FUNCTIONS_PATH.'/inc.showuser.php');
	  }
	  break;
	  
	//##########################################################################################################################
	// Hier wird das Tippspiel Ranking angezeigt
	 
	  case "showtipranking":
	    $showUser_config=$joomleague->getTemplateConfig("show_user.tpl");
	    $showTipRanking_config=$joomleague->getTemplateConfig("show_tip_ranking.tpl");
	    $table_config=$joomleague->getTemplateConfig("show_table.tpl");
	  	$limit = ($showTipRanking_config['limit']>0) ? intval($showTipRanking_config['limit']) : 10;
	  	//maybe later limitstart can be used if $tipRanking->getTippRanking($mode, $round) can be called with a limit 
	  	//$limitstart = intval(mosGetParam($_REQUEST, 'limitstart', 0));
	  	$page = intval(mosGetParam($_REQUEST, 'page', 0));
	    if ( defined('JL_PREDICTION') && TRUE===JL_PREDICTION ){
	
	      // fetch GET params
	      $round = ($r == 0) ? $joomleague->current_round : $r;
	      $mode = mosGetParam($_REQUEST, 'mode', '');
	      
	      // update PageTitle
	      if($mode == 'all'){
	        $mainframe->setPageTitle(_JL_PAGE_TITLE_TIP_RANKING_ALL);
	//        $mainframe->appendPathWay(_JL_PAGE_TITLE_TIP_RANKING_ALL);
	      }
	      else{
	        //ranking this round
	        $mainframe->setPageTitle(_JL_PAGE_TITLE_TIP_RANKING_DAY);
	//        $mainframe->appendPathWay(_JL_PAGE_TITLE_TIP_RANKING_DAY);
	      }
	
	      // calculate tipranking 
	
	      $joomleague->getPredictionConfig();
	      $round = ($r == 0) ? $joomleague->current_round : $r;
	      $rounds = $joomleague->getRoundNames();
	
	      if (mosGetParam($_REQUEST, 'part', '')!='') {
	        $part=intval(mosGetParam($_REQUEST, 'part', 0));
	        if ($part==1) {
	      	  $from = 1;
	    	  $to = intval(count($rounds)/2);
	        }
	        elseif ($part==2) {
	    	  $from = intval(count($rounds)/2)+1;
	    	  $to = count($rounds);
	        }
	        else {
	     	  $from = intval(mosGetParam($_REQUEST, 'from', 1));
	    	  $to = intval(mosGetParam($_REQUEST, 'to', $round));
	        }
	      } else {
	        if ($joomleague->overview==0) $part=0; else if ($round > intval(count($rounds)/2)) $part=2; else $part=1;
	    	$to = intval(mosGetParam($_REQUEST, 'to', $round));
	        if ($part==1) {
	      	  $from = 1;
	        }
	        elseif ($part==2) {
	    	  $from = intval(count($rounds)/2)+1;
	        }
	        else {
	     	  $from = intval(mosGetParam($_REQUEST, 'from', 1));
	        }
	      }
	    
	      $tipRanking = new TipRanking();
	      $tipRanking->setProject($joomleague);
	      $showTipper = $tipRanking->getTippRanking($mode,$to,$from,$limit,$page,'',0,$showTipRanking_config['show_all_user']);
	      $anzahltipper = $tipRanking->getTippRanking($mode,$to,$from,$limit,$page,'countUser',0,$showTipRanking_config['show_all_user']);
	      unset ($tipRanking);
	      
	      $rounds = $joomleague->getRoundNames();
	      $pageNav=$joomleague->pagenav($jl_func,count($rounds), $to, '', $mode);
	      $pageNav2=$joomleague->pagenav2($jl_func, count($rounds), $to, '', $mode);
	
	      $current_round=$round;
	      require(getTemplateFile(JL_TEMPLATE_PATH, 'show_tip_ranking.tpl.php'));
	      unset($showTipper);
	    }
	    
	// Tippspiel Ranking Ende
	//##########################################################################################################################
	// Start der Tipp�bersicht
	    
	  break;
	//##########################################################################################################################  
	    case "showtipresults":
	    if ( defined('JL_PREDICTION') && TRUE===JL_PREDICTION ){
	    $joomleague->getPredictionConfig();
	    $showTipResults_config=$joomleague->getTemplateConfig("show_tip_results.tpl");
	    $table_config=$joomleague->getTemplateConfig("show_table.tpl");
	  	$limit = ($showTipResults_config['limit']>0) ? intval($showTipResults_config['limit']) : 10;
	  	//maybe later limitstart can be used if $tipRanking->getTippRanking($mode, $round) can be called with a limit 
	  	//$limitstart = intval(mosGetParam($_REQUEST, 'limitstart', 0));
	  	$page = intval(mosGetParam($_REQUEST, 'page', 0));
	    
	    // reprogrammed to use Tip at DB
	 	$points=array();
		$totalpoints=array();
		$totaltips=array();
		$username=array();
	   	// neue variable $joker als array 2007/05/05 *gucky*
	   	$joker=array();
	   	$mainframe->setPageTitle(_JL_PAGE_TITLE_TIP_OVERVIEW);
	//    $mainframe->appendPathWay(_JL_PAGE_TITLE_TIP_OVERVIEW);
	   	$round = ($r == 0) ? $joomleague->current_round : $r;
	    $teams = $joomleague->getTeams();
	    $rounds = $joomleague->getRoundNames();
	// 	$thistime=date("Y-m-d H:i:s");
	    $matches = $joomleague->getResults($round);
	    $query = "SELECT id
	                FROM #__joomleague_rounds
	               WHERE matchcode = $round AND project_id = $joomleague->id";
	    $database->setQuery($query);
	    $rlist = $database->loadResultArray();
	    $roundlist = implode(",",$rlist);
	    $anzahluser = 0;
	
	    if ($uid!="") $query = " AND u.id = $uid"; else {
	/*****
	      $query = sprintf("SELECT count(u.id)
	                          FROM #__users u
	                          LEFT JOIN #__joomleague_tip_members tm ON u.id = tm.user_id
	                         WHERE tm.approved = 1 AND tm.project_id = %s", $joomleague->id);
	*****/
	      if ((isset($showTipResults_config['show_all_user'])) && $showTipResults_config['show_all_user']) {
	        $limitstart = ($page*$limit);
	        $limitoffset = $limit;
	        $query = sprintf("SELECT u.id as user_id, u.username
	                            FROM #__users u
	                            LEFT JOIN #__joomleague_tip_members tm ON u.id = tm.user_id
	                           WHERE tm.approved = 1 AND tm.project_id = %s LIMIT %s,%s", $joomleague->id, $limitstart, $limitoffset);
	        $database->setQuery($query);
	        $user = $database->loadObjectList();
	        foreach($user as $uservar) {
	            $templist[$uservar->user_id]=$uservar->user_id;
	            if(!array_key_exists($uservar->user_id, $totalpoints)){
	              $username[$uservar->user_id] = $uservar->username;
	              $totalpoints[$uservar->user_id] = 0;
	              $totaltips[$uservar->user_id] = 0;
	            }
	        }
	        $userlist = implode(",",$templist);
	        $query = " AND u.id IN ($userlist)";
	      } else {
	        $query = sprintf("SELECT u.id
	                            FROM #__users u
	                       LEFT JOIN #__joomleague_tip_results tr ON u.id = tr.user_id
	                       LEFT JOIN #__joomleague_tip_members tm ON tr.user_id = tm.user_id
	                       LEFT JOIN #__joomleague_matches m on m.match_id = tr.match_id
	                           WHERE tm.approved = 1 AND tr.project_id = %s AND m.round_id IN (%s)
	                           GROUP By u.id", $joomleague->id, $roundlist);
	        $database->setQuery($query);
	        $results = $database->loadResultArray();
	        $anzahluser = count($results);
	        $userlist = '';
	        if (count($results)>0) $userlist = implode(",",$results);
	        if ($anzahluser>$limit) {
	          $limitstart = ($page*$limit);
	          $limitoffset = $limit;
	          $query = sprintf("SELECT u.id as user_id, u.username as username
	                              FROM #__users u
	                         LEFT JOIN #__joomleague_tip_results tr ON u.id = tr.user_id
	                         LEFT JOIN #__joomleague_tip_members tm ON tr.user_id = tm.user_id
	                         LEFT JOIN #__joomleague_matches m on m.match_id = tr.match_id
	                             WHERE tm.approved = 1 AND tr.project_id = %s AND m.round_id IN (%s)
	                             GROUP By u.id LIMIT %s,%s", $joomleague->id, $roundlist, $limitstart, $limitoffset);
	          $database->setQuery($query);
	          $user = $database->loadObjectList();
	          foreach($user as $uservar) {
	            if(!array_key_exists($uservar->user_id, $totalpoints)){
	              $username[$uservar->user_id] = $uservar->username;
	              $totalpoints[$uservar->user_id] = 0;
	              $totaltips[$uservar->user_id] = 0;
	            }
	          }
	          
	          $query = sprintf("SELECT u.id as user_id
	                              FROM #__users u
	                         LEFT JOIN #__joomleague_tip_results tr ON u.id = tr.user_id
	                         LEFT JOIN #__joomleague_tip_members tm ON tr.user_id = tm.user_id
	                         LEFT JOIN #__joomleague_matches m on m.match_id = tr.match_id
	                             WHERE tm.approved = 1 AND tr.project_id = %s AND m.round_id IN (%s)
	                             GROUP By u.id LIMIT %s,%s", $joomleague->id, $roundlist, $limitstart, $limitoffset);
	          $database->setQuery($query);
	          $user = $database->loadResultArray();
	          $userlist = implode(",",$user);
	        }
	        $query = " AND u.id IN ($userlist)";
	      }
	    }
	
		// Zeile (m.alt_decision as decision,) in SQL-Abfrage eingef�gt --> stefan47110815 (23.04.2007)
				$query = "SELECT m.match_id,                  
	                         m.matchpart1_result as e1, 
	                         m.matchpart2_result as e2, 
							 m.alt_decision as decision,
	                         m.matchpart1_result_decision AS v1, 
	                         m.matchpart2_result_decision AS v2, 
	                         tip.tip_home, 
	                         tip.tip_away, 
	                         tip.tip,
	                         tip.joker,
	                         pp.point,
	                         u.username AS username, 
	                         u.id AS user_id 
	                FROM #__joomleague_tip_results tip 
	              LEFT JOIN #__joomleague_matches m on m.match_id = tip.match_id
	              Left JOIN #__users u on u.id = tip.user_id
	              LEFT JOIN #__joomleague_predictiongame_points pp ON tip.id = pp.tipp_id
	              LEFT JOIN #__joomleague_tip_members tm ON tm.user_id = tip.user_id  AND tm.project_id = m.project_id
	                  WHERE m.project_id = ".$joomleague->id. " AND 
	                        tm.approved = 1 AND 
	                        m.round_id IN ($roundlist)".$query;
	
	      $database->setQuery($query);
	      $rows = $database->loadObjectList();
	      if (count($rows) > 0) {
	        foreach($rows as $row) {
	      	  $points[$row->user_id][$row->match_id]=0;
	      	  if(!array_key_exists($row->user_id,$totalpoints)) {
	            $username[$row->user_id] = $row->username;
	            $totalpoints[$row->user_id]=0;
	            $totaltips[$row->user_id]=0;
	          }
	          // $joker des users bekommt match_id zugeteilt wenn gesetzt 2007/05/05 *gucky*
	          if ($row->joker==1) $joker[$row->user_id] = $row->match_id;
	          $points[$row->user_id][$row->match_id]=$row->point;
	          $totalpoints[$row->user_id]+=$points[$row->user_id][$row->match_id];
	          $totaltips[$row->user_id]++;
	        }
	      }
	/*****
	******/
	      if (!empty($username)) asort ($username);
	/*****
	      if (count($username)>$limit) {
	        $limitstart=($page*$limit)+1;
	        $count = 1;
	        foreach($username  as $key=>$val) {
	          if (($count<$limitstart) || ($count>=$limitstart+$limit)) {
	            unset($username[$key]);
	            unset($points[$key]);
		        unset($totalpoints[$key]);
		        unset($totaltips[$key]);
		        unset($joker[$key]);
	          }
	          $count++;
	        }
	      }
	      print_r($points);
	*****/
		  $pageNav=$joomleague->pagenav($jl_func,count($rounds), $round, $uid); 
	    $pageNav2=$joomleague->pagenav2($jl_func, count($rounds), $round, $uid);
				 
		  $current_round=$round; 
	
		  require(getTemplateFile(JL_TEMPLATE_PATH, 'show_tip_results.tpl.php'));
		}
	// Tipp�bersicht Ende
	
	//##########################################################################################################################
	  
	  break;
	
	
	// save prediction user
	   
	  case "saveuser":
	    $showUser_config=$joomleague->getTemplateConfig("show_user.tpl");
	    $filedir = ($showUser_config['picture_dir']) ? $showUser_config['picture_dir'] :'images/joomleague/users';
	    $savedata=intval(mosGetParam($_POST, 'save_data', 0));
	    $pid = intval(mosGetParam($_REQUEST, 'p', 0));
	    $fav_team=intval(mosGetParam($_POST, 'fav_team', 0));
	    $champ_tip = intval(mosGetParam($_REQUEST, 'champ_tip', 0));
	    $slogan = mosGetParam($_REQUEST, 'slogan', '');
	    $reminder = intval(mosGetParam($_REQUEST, 'reminder', 0));
	    $receipt = intval(mosGetParam($_REQUEST, 'receipt', 0));
	    $tipadmin = intval(mosGetParam($_REQUEST, 'tipadmin', 0));
	    $picture = mosGetParam($_REQUEST, 'picture', '');
	    $oldpicture = mosGetParam($_REQUEST, 'oldpicture', '');
	    
	  	if ($savedata == 1) {
	  		if ($fav_team==0) {
	      setCookie("joomleague_user_fav_team_p_$pid", FALSE );  		
	      $fav_team='NULL';
	      }
	  		if ($fav_team > 0) {
	      $query = sprintf("SELECT team_id FROM #__joomleague_team_joomleague WHERE id = %s", $fav_team);
	      $database->setQuery($query);
	      $favorite = $database->loadResult();
	      setCookie("joomleague_user_fav_team_p_$pid", $favorite, time() + 360000000 );
	      }
	  		if ($champ_tip==0) $champ_tip='NULL';
	  		if ($slogan=='') $slogan='NULL'; else $slogan = "'".$slogan."'";
		    $query=sprintf("UPDATE #__joomleague_tip_members SET fav_team=%s, slogan=%s, reminder=%s, receipt=%s, tipadmin=%s",$fav_team, $slogan, $reminder, $receipt, $tipadmin);
	
	        $query1 = "SELECT m.match_date as match_date 
	                    FROM #__joomleague_matches m
	                   WHERE m.project_id = ".$joomleague->id. " 
	                     AND m.match_date > 0
	                ORDER BY m.match_date LIMIT 1"; 
	        $database->setQuery($query1);
	        $saisonstart = $joomleague->getTimestamp($database->loadResult());
	        $thistime=$joomleague->getTimestamp('',1);
	
		    if ($saisonstart > $thistime) {
		      $query.=sprintf(", champ_tip=%s", $champ_tip);
	        }
	
		    $query.=sprintf(" WHERE user_id=%s AND project_id=%s", $uid, $joomleague->id);
		    $database->setQuery($query);
		    $database->query();
		    $query="UPDATE #__joomleague_tip_members SET picture=";
		    if ($picture=='') { $query.= "NULL";} else { $query .= "'$picture'";}
				$query.=" WHERE user_id = $uid";
				$database->setQuery($query);
		    $database->query();
	
		}
		else {
			if ($oldpicture != $picture && file_exists(_JOOMLA_JL_PATH.'/'.$filedir.'/'.$picture)&&$picture!='') {
				unlink (_JOOMLA_JL_PATH.'/'.$filedir.'/'.$picture);
				unlink (_JOOMLA_JL_PATH.'/'.$filedir.'/tn_'.$picture);
			}
		}
	//    showUser; 
	    mosRedirect(sprintf(JL_COMPONENT_LINK."&func=showUser&p=%s&uid=%s".JL_ITEMID_SUFFIX,$joomleague->id,$uid));
	    
	// save prediction user ends
	//##########################################################################################################################
	    
	  break;
	// Tippspiel Regeln
	
	  case "showtiprules":
	  
	    $mainframe->setPageTitle(_JL_RULES);
	    $v = new JoomLeagueVersion();
	    $joomleague->getPredictionConfig();
	    $joomleague->tip_tg=0;
	
	    require(getTemplateFile(JL_TEMPLATE_PATH, 'show_rules.tpl.php'));
	    
	// Tippspiel Regeln Ende
	//##########################################################################################################################
	    
	  break;  
	  case "dotips":
	  if ( defined('JL_PREDICTION') && TRUE===JL_PREDICTION ){
	    
	    $doTips_config=$joomleague->getTemplateConfig("do_tips.tpl");
	    
	    $showUser_config=$joomleague->getTemplateConfig("show_user.tpl");
	    $mainframe->setPageTitle(_JL_PAGE_TITLE_DO_TIP);
	    
	  	$usetipadmin = ($doTips_config['use_tip_admin']>0) ? intval($doTips_config['use_tip_admin']) : 0;
	  	$joomleague->getPredictionConfig($usetipadmin);
	  	$user_is_tippadmin = (isset($my->id) && $my->id > 0 && in_array($my->id, $joomleague->tip_admin)) ? 1 : 0;
	    
	    require (JL_FUNCTIONS_PATH.'/inc.dotips.php');
	  } //joomleague_tip
	    
	//Registrierung Ende
	//##########################################################################################################################
	
	
	//Ende des Tippbereichs
	//##########################################################################################################################
	//##########################################################################################################################
	//##########################################################################################################################
	  
	  break;
	  //##########################################################################################################################
	// Um doppelte Tipps zu vermeiden wird der User automatisch weitergeleitet
	
	  case "savedtips":
	    $mainframe->setPageTitle(_JL_PAGE_TITLE_TIPS_SAVED);
	//    $mainframe->appendPathWay(_JL_PAGE_TITLE_TIPS_SAVED);
	    
	    require(getTemplateFile(JL_TEMPLATE_PATH, 'tips_saved.tpl.php'));
	    break;
	    
	  case 'ical':
	   require JL_FUNCTIONS_PATH.'/ical.php';
     manageIcal();
     break;  
	}
	
	// footer
	if ( isset( $overall_config['show_footer'] ) && $overall_config['show_footer'] == "1" && $regular_output) {
	  include_once(getTemplateFile(JL_TEMPLATE_PATH, 'show_footer.tpl.php'));
	}
}

/**
 * manage project independant functions
 *
 * @param string $jl_func
 * @return bool true if $jl_func was matched
 */
function switchGeneralFunc( $jl_func )
{
  global $my, $mainframe, $database;
  global $joomleague, $joomleague_tabs, $jlgConfig, $htmlHelper;

  $regular_output = (intval(mosGetParam($_REQUEST, 'no_html', 0)) == 1) ? false : true;
  
  $folder = 'default';

	switch( $jl_func )
  {
  	case 'frontpage':
      // tell program path to templates for this project
      define('JL_TEMPLATE_PATH', JL_FRONTEND_PATH.'/frontend/'.$folder);
      // tell program where to find images / css 
      define('JL_TEMPLATE_FOLDERS_URL', _JOOMLA_JL_LIVE_SITE.'/components/com_joomleague/frontend/'.$folder);
      // frontpage with summary of projects
      require JL_FUNCTIONS_PATH.'/frontpage.php';
      showJoomleagueStart($jlgConfig);
      return true;
  }
}
